package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go.uber.org/zap"
	ijwt "jk-time/webook/internal/web/jwt"
	"net/http"
	"strings"
)

type LoginJWTMiddlewareBuilder struct {
	ignorePaths []string
	ijwt.Handler
}

func NewLoginJWTMiddlewareBuilder(handler ijwt.Handler) *LoginJWTMiddlewareBuilder {
	return &LoginJWTMiddlewareBuilder{
		ignorePaths: make([]string, 0, 10),
		Handler:     handler,
	}
}
func (l *LoginJWTMiddlewareBuilder) IgnorePaths(path string) *LoginJWTMiddlewareBuilder {
	l.ignorePaths = append(l.ignorePaths, path)
	return l
}
func (l *LoginJWTMiddlewareBuilder) CheckLogin() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		path := ctx.Request.URL.Path
		for _, ignorePath := range l.ignorePaths {
			if path == ignorePath || strings.Contains(path, ignorePath) {
				return
			}
		}

		tokenStr := l.ExtractToken(ctx)
		uc := &ijwt.UserClaims{}
		if uc.UserAgent != ctx.GetHeader("User-Agent") {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		token, err := jwt.ParseWithClaims(tokenStr, uc, func(token *jwt.Token) (interface{}, error) {
			return []byte("k6CswdUm77WKcbM68UQUuxVsHSpTCwgK"), nil
		})
		if err != nil {
			// 没登录，Authorization 中的内容是乱传的
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		if token == nil || !token.Valid || uc.Uid == 0 {
			// token 解析出来了，但是 token 可能是非法的，或者过期了的
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		cnt := l.CheckSession(ctx, uc.Ssid)
		if cnt > 0 {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			zap.L().Error("该用户已退出")
			return
		}
		ctx.Set("claims", uc)
		//刷新token的过期时间
		//expireTime, err := uc.GetExpirationTime()
		//if err != nil {
		//	ctx.AbortWithStatus(http.StatusUnauthorized)
		//	return
		//}
		//if expireTime.Before(time.Now()) {
		//	ctx.AbortWithStatus(http.StatusUnauthorized)
		//	return
		//}
	}
}
